import React, { useState, Component } from 'react';
import { Row, Col, Drawer, Breadcrumb, Table, Pagination, notification, Input, InputNumber, Popconfirm, Form, Typography, Button } from 'antd'
import axios from 'axios';
import cookies from 'react-cookies'
import './Commodity.css';
import ButtonGroup from 'antd/lib/button/button-group';
import { DownloadOutlined, PlusOutlined } from '@ant-design/icons';
import { saveAs } from 'file-saver';

class Commdoity extends Component {
    state = {
        pagination: {
            current: 1,
            pageSize: 8,
            total: 0
        },
        loading: false,
        originData: [],
        "Cname": "小鸡蘑菇",
        "Price": 3.00,
        "BarCode": "89879123",
        "Specification": "80g",
        "Unit": "包",
        "Ctype": null,
        Visible: false
    };

    Download = () => {
        //     axios
        //         .get('http://localhost:5000/ant/Store/1/GetTable')
        //         .then(response=>{
        //             var a = new Blob([response.data]) 
        //             var b = new File(a,'download.csv',)
        //         })
        saveAs(`http://localhost:5500/ant/ant/Store/${cookies.load('userStore')}/GetTable`, "test.csv")

        //   const xhr = new XMLHttpRequest()
        //   const url = 'http://localhost:5000/ant/Store/1/GetTable'
        //   xhr.open('get', url, false) // 同步请求
        //   xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
        //   xhr.send()
        //   console.log(xhr.responseText);

        //   const res = JSON.parse(xhr.responseText)
        //    res.body
    }

    //搜索数据
    seachCommodity = (key) => {

        this.setState({ loading: true })
        const { pagination } = this.state; axios
            .get(`http://localhost:5500/ant/ant/Store/${cookies.load('userStore')}/GetCommodity?pageSize=${pagination.pageSize}&current=${pagination.current}&key=${key}`)
            .then(response => {
                var newData = []
                for (const key in response.data.data) {
                    if (Object.hasOwnProperty.call(response.data.data, key)) {
                        const item = response.data.data[key];
                        item.key = key
                        newData = [...newData, item]
                    }
                }
                this.setState({ originData: [...newData] })
                this.setState({
                    pagination: {
                        current: response.data.current,
                        pageSize: response.data.pageSize,
                        total: response.data.count,
                    }
                })
                this.setState({ loading: false })
            })
            .catch(err => {
                this.setState({ originData: [] })
                this.setState({
                    pagination: {
                        current: pagination.current,
                        pageSize: pagination.pageSize,
                        total: pagination.total,
                    }
                })
                this.setState({ loading: false })
            })

    }
    GetComData = () => {

        this.setState({ loading: true })
        const { pagination } = this.state;
        axios
            .get(`http://localhost:5500/ant/ant/Store/${cookies.load('userStore')}/GetCommodity?pageSize=${pagination.pageSize}&current=${pagination.current}`)
            .then(response => {
                var newData = []
                for (const key in response.data.data) {
                    if (Object.hasOwnProperty.call(response.data.data, key)) {
                        const item = response.data.data[key];
                        item.key = key
                        newData = [...newData, item]
                    }
                }
                this.setState({ originData: [...newData] })
                this.setState({
                    pagination: {
                        current: response.data.current,
                        pageSize: response.data.pageSize,
                        total: response.data.count,
                    }
                })
                this.setState({ loading: false })
            })
    }
    //加载时去请求数据
    componentDidMount() {
        this.GetComData();
    }

    //换页
    handleTableChange = (paginationtemp, filters, sorter) => {
        const { pagination } = this.state
        console.log(pagination);
        axios
            .get(`http://localhost:5500/ant/ant/Store/${cookies.load('userStore')}/GetCommodity?pageSize=${pagination.pageSize}&current=${paginationtemp}`)
            .then(response => {
                var newData = []
                for (const key in response.data.data) {
                    if (Object.hasOwnProperty.call(response.data.data, key)) {
                        const item = response.data.data[key];
                        item.key = key
                        newData = [...newData, item]
                    }
                }

                this.setState({ originData: [...newData] })
                this.setState({
                    pagination: {
                        current: paginationtemp,
                        pageSize: pagination.pageSize,
                        total: response.data.count,
                    }
                })
                this.setState({ loading: false })
            })
    }

    showDrawer = () => {
        this.setState({
            Visible: true,
        });
    };
    onClose = () => {
        this.setState({
            Visible: false
        });
    };
    AddCom = () => {
        const { Cname, Price, BarCode, Specification, Unit, Ctype } = this.state
        var data = {

            "Cname": Cname,
            "Price": Price * 1,
            "BarCode": BarCode,
            "Specification": Specification,
            "Unit": Unit,
            "Ctype": Ctype
        }
        axios
            .post(`http://localhost:5500/ant/ant/Store/${cookies.load('userStore')}/AddCommodity`, data)
            .then(response => {
                notification['success']({
                    message: '添加成功',
                    description: ''

                })
                this.onClose()
                this.GetComData()
            })
    }

    render() {
        // const link = `http://localhost:5500/ant/ant/Store/${cookies.load('userStore')}/GetTable`
        const { originData, pagination } = this.state

        const EditableCell = ({
            editing,
            dataIndex,
            title,
            inputType,
            record,
            index,
            children,
            ...restProps
        }) => {
            const inputNode = inputType === 'number' ? <InputNumber /> : <Input />;
            return (
                <td {...restProps}>
                    {editing ? (
                        <Form.Item
                            name={dataIndex}
                            style={{
                                margin: 0,
                            }}
                            rules={[
                                {
                                    required: true,
                                    message: `Please Input ${title}!`,
                                },
                            ]}
                        >
                            {inputNode}
                        </Form.Item>
                    ) : (
                        children
                    )}
                </td>
            );
        };

        const EditableTable = () => {
            let [form] = Form.useForm();
            const [data, setData] = useState(originData);
            const [editingKey, setEditingKey] = useState('');

            const isEditing = (record) => record.key === editingKey;

            const edit = (record) => {
                form.setFieldsValue({
                    name: '',
                    age: '',
                    address: '',
                    ...record,
                });
                setEditingKey(record.key);
            };
            const cancel = () => {
                setEditingKey('');
            };
            const save = async (key) => {
                try {
                    const row = await form.validateFields();
                    const newData = [...data];
                    const index = newData.findIndex((item) => key === item.key);


                    if (index > -1) {
                        const item = newData[index];
                        newData.splice(index, 1, { ...item, ...row });
                        setData(newData);
                        setEditingKey('');
                    } else {
                        newData.push(row);
                        setData(newData);
                        setEditingKey('');
                    }



                    for (let index = 0; index < newData.length; index++) {
                        newData[index].price = parseFloat(newData[index].price)
                    }


                    axios
                        .put(`http://localhost:5500/ant/ant/Store/${cookies.load('userStore')}/UpdateCommodity`, newData[index])
                        .then(response => {
                            notification['success']({
                                message: '修改成功',
                                description: '已提交修改'
                            })
                        })
                        .catch(err => {
                            notification['warning']({
                                message: '修改失败',
                                description: '请稍后再试'
                            })

                            return;
                        })
                } catch (errInfo) {
                    console.log('Validate Failed:', errInfo);
                }


            };

            const columns = [
                {
                    title: '编码',
                    dataIndex: 'barCode',
                    key: 'barCode',
                    render: text => <span>{text}</span>,
                    editable: true,
                },
                {
                    title: '名称',
                    dataIndex: 'cname',
                    key: 'cname',
                    render: text => <span style={{ color: '#569cc5' }}>{text}</span>,
                    editable: true
                },
                {
                    title: '价格',
                    dataIndex: 'price',
                    key: 'price',
                    render: text => parseFloat(text).toFixed(2),
                    editable: true
                },
                {
                    title: '规格',
                    dataIndex: 'specification',
                    key: 'specification',
                    editable: true
                },
                {
                    title: '单位',
                    dataIndex: 'unit',
                    key: 'unit',
                    editable: true
                },
                {
                    title: '操作',
                    width: '12%',
                    dataIndex: 'operation',
                    render: (_, record) => {
                        const editable = isEditing(record);
                        return editable ? (
                            <span>
                                <span
                                    // href="javascript:;"
                                    onClick={() => save(record.key)}
                                    style={{
                                        marginRight: 8,
                                        color: '#4a9cd6'
                                    }}
                                >
                                    保存
                                 </span>

                                <Popconfirm title="确定取消编辑？?" onConfirm={cancel}>
                                    <span style={{ color: '#4a9cd6' }}>取消</span>
                                </Popconfirm>
                            </span>
                        ) : (
                            <Typography.Link disabled={editingKey !== ''} onClick={() => edit(record)}>
                                修改
                            </Typography.Link>
                        );
                    },
                },
            ];
            const mergedColumns = columns.map((col) => {
                if (!col.editable) {
                    return col;
                }

                return {
                    ...col,
                    onCell: (record) => ({
                        record,
                        inputType: col.dataIndex === 'age' ? 'number' : 'text',
                        dataIndex: col.dataIndex,
                        title: col.title,
                        editing: isEditing(record),
                    }),
                };
            });
            return (
                <Form form={form} component={false}>
                    <Table
                        components={{
                            body: {
                                cell: EditableCell,
                            },
                        }}
                        bordered
                        dataSource={data}
                        columns={mergedColumns}
                        rowClassName="editable-row"
                        pagination={{
                            onChange: cancel,
                        }}
                    />
                </Form>
            );
        };
        return <div>
            <Row>
                <Col span={24} style={{ padding: '20px' }}>
                    <Breadcrumb>
                        <Breadcrumb.Item><span style={{ fontSize: '20px' }}>后台</span></Breadcrumb.Item>
                        <Breadcrumb.Item><span style={{ fontSize: '20px' }}>商品</span></Breadcrumb.Item>
                    </Breadcrumb>
                </Col>
            </Row>
            <Row>
                <Col span={22} offset={1}>
                    <Input
                        placeholder="编码/名称"
                        onKeyUp={input => {
                            if (input.keyCode === 13) this.seachCommodity(input.currentTarget.value)
                        }}
                    >
                    </Input>
                    <ButtonGroup style={{ padding: '5px 0px' }}>
                        {/* <NavLink to={link} icon={<DownloadOutlined/>}>导出数据</NavLink> */}
                        <Button type='primary' onClick={() => this.Download()} icon={<DownloadOutlined />}>导出数据</Button>
                        &nbsp;&nbsp;
                        <Button type='primary' onClick={() => this.showDrawer()} icon={<PlusOutlined />}>添加商品</Button>
                    </ButtonGroup>
                    <EditableTable></EditableTable>
                    <Pagination
                        current={pagination.current}
                        pageSize={pagination.pageSize}
                        defaultCurrent={1}
                        total={pagination.total}
                        onChange={this.handleTableChange}
                    />
                </Col>
            </Row>

            <Drawer
                title="录入商品信息"
                width={300}
                onClose={this.onClose}
                visible={this.state.Visible}
                bodyStyle={{ paddingBottom: 80 }}
                footer={
                    <div
                        style={{
                            textAlign: 'right',
                        }}
                    ><Button onClick={this.AddCom} type="primary" style={{ marginRight: 8 }}>
                            确定
                                </Button>
                    </div>}
            >

                商品名称： <Input onChange={(input) => this.setState({ Cname: input.currentTarget.value })}></Input>
                商品售价：<Input onChange={(input) => this.setState({ Price: input.currentTarget.value })}></Input>
                商品条码：<Input onChange={(input) => this.setState({ BarCode: input.currentTarget.value })}></Input>
                商品规格：<Input onChange={(input) => this.setState({ Specification: input.currentTarget.value })}></Input>
                商品单位：<Input onChange={(input) => this.setState({ Unit: input.currentTarget.value })}></Input>

            </Drawer>

        </div>


    }
}

export default Commdoity;
